package com.jianguozh.difs.support.api.superior;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.constant.SecurityConstant;
import com.jianguozh.difs.framework.validator.group.AddGroup;
import com.jianguozh.difs.framework.validator.group.UpdateGroup;
import com.jianguozh.difs.support.api.superior.dto.CorporateDto;
import com.jianguozh.difs.support.api.superior.vo.CorporateVo;
import com.jianguozh.difs.support.service.org.entity.Corporate;
import com.jianguozh.difs.support.service.org.service.ICorporateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * <p>
 * 餐饮主体 前端控制器
 * </p>
 *
 * @author hanrs
 * @since 2022-03-17
 */
@RestController
@RequestMapping("/corporate")
public class CorporateController extends BaseController {

    @Autowired
    ICorporateService corporateService;

    /**
     * 由id获取对象
     */
    @GetMapping("/{id}")
    public R<Corporate> get(@PathVariable String id) {
        return success(corporateService.getById(id));
    }

    /**
     * 新增
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_SUPERIOR + "')")
    @PostMapping("")
    public R<Corporate> add(@RequestBody @Validated(value = {AddGroup.class}) CorporateDto corporateDto) {
        long count = corporateService.count(new LambdaQueryWrapper<Corporate>().eq(Corporate::getCorporateName, corporateDto.getCorporateName()));
        if (count > 0) {
            return failed("已经存在'" + corporateDto.getCorporateName() + "'的主体.");
        }

        Corporate entity = new Corporate();
        BeanUtil.copyProperties(corporateDto, entity);
        boolean result = corporateService.save(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 修改
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_SUPERIOR + "')")
    @PutMapping("/{id}")
    public R<Corporate> update(@RequestBody @Validated(value = {UpdateGroup.class}) CorporateDto corporateDto) {
        long count = corporateService.count(new LambdaQueryWrapper<Corporate>().eq(Corporate::getCorporateName, corporateDto.getCorporateName()).ne(Corporate::getId, corporateDto.getId()));
        if (count > 0) {
            return failed("已经存在'" + corporateDto.getCorporateName() + "'的主体.");
        }

        Corporate entity = new Corporate();
        BeanUtil.copyProperties(corporateDto, entity);
        boolean result = corporateService.updateById(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 批量删除
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_SUPERIOR + "')")
    @DeleteMapping("/batch")
    public R<Boolean> deleteBatch(@RequestParam(value = "ids[]") String[] ids) {
        boolean result = corporateService.removeByIds(Arrays.asList(ids));
        return result ? success(true) : failed("操作失败.");
    }

    /**
     * 单个删除
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_SUPERIOR + "')")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable String id) {
        boolean result = corporateService.removeById(id);
        return result ? success(true) : failed("操作失败.");
    }

    /**
     * 条件分页查询
     */
    @GetMapping("/page-query")
    public R<IPage<CorporateVo>> pageQuery(HttpServletRequest request,
                                           @RequestParam(name = "corporateName", required = false) String corporateName) {

        LambdaQueryWrapper<Corporate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(corporateName))
            lambdaQueryWrapper.like(Corporate::getCorporateName, corporateName);

        IPage page = resolvePage(request);
        IPage<CorporateVo> result = corporateService.page(page, lambdaQueryWrapper).convert(o -> {
            CorporateVo vo = new CorporateVo();
            BeanUtil.copyProperties(o, vo);
            vo.setDefaultManager(corporateService.getDefaultManager(vo.getId()));
            return vo;
        });
        return success(result);
    }


}
